--
-- Author: yawei.zhu
-- Date: 2018-06-05 15:49:35
--
-- PvpChampionView
--
local PvpChampionReady = import(".PvpChampionReady")
local PvpChampionSearch = import(".PvpChampionSearch")
local PvpChampionForm = import(".PvpChampionForm")
local PvpChampionSeek = import(".PvpChampionSeek")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.ChampionUI

function ClassRef:init()
	self._ui.Button_close:addClickEventListener(function()
		executeFunc(self._onCloseView)
	end)

	self._ui.Button_more:addClickEventListener(function()
		display.pushToast( L("lua_code_text_458") )
	end)

	self._championReady = PvpChampionReady.new(self._ui.ready)
	self._championReady:onOperate(function(op, data)
		executeFunc(self._onOperate, op, data)
	end)
	self._championSearch = PvpChampionSearch.new(self._ui.search)
	self._championSearch:onOperate(function(op, data)
		executeFunc(self._onOperate, op, data)
	end)
	self._championForm = PvpChampionForm.new(self._ui.form)
	self._championForm:onOperate(function(op, data)
		executeFunc(self._onOperate, op, data)
	end)
	self._championSeek = PvpChampionSeek.new(self._ui.seek)
	self._championSeek:onOperate(function(op, data)
		executeFunc(self._onOperate, op, data)
	end)

 	local championPanel = self._ui.first:getChildByName("Panel")
    championPanel:addClickEventListener(function(sender)
    	local endPos = sender:getTouchEndPosition()
    	-- dump(endPos)
    	local playArmature = championPanel:getChildByName("Node_1"):getChildByTag(100)
    	if playArmature and playArmature:containWorldPoint(endPos.x, endPos.y) then
    		UIHandler:showHeadMenu({online=true, attr=self._rightBaseInfo, pos = cc.p(300, endPos.y)})
    	end
    end)
end

-- 定时器
function ClassRef:_tick(dt)
	if not self._throneGame then return end

	if self._championSeek:isVisible() then
		self._championSeek:tick(self._throneGame.regCloseTime)
	end
	if self._championSearch:isVisible() then
		self._championSearch:tick(self._throneGame.regCloseTime)
	end
	if self._championReady:isVisible() then
		self._championReady:tick(self._throneGame)
	end
end

-- 更新左边显示
function ClassRef:updateChampionCharacter(info)
	local info = info or self._curThroneInfo

	local championPanel = self._ui.first:getChildByName("Panel")

	local txtTitle = championPanel:getChildByName("tlt")
	local txtMode = championPanel:getChildByName("text_mode")
	local imageBg = championPanel:getChildByName("Image")
	local firstPanel = championPanel:getChildByName("Panel_first")
	local txtDesc = firstPanel:getChildByName("tlt")
	local txtName = firstPanel:getChildByName("name")

	txtTitle:setString("")
	txtMode:setString("")
	txtDesc:setString(L("champion_notice7"))
	firstPanel:setVisible(true)

	-- 标题 根据_selectDay查找配置
	local throneConfig = GD:queryThroneByDay(info.day)
	if throneConfig then
		txtTitle:setString( L(throneConfig.name) )
		txtMode:setString( L(throneConfig.des) )
		imageBg:loadTexture( Res.ThroneBgPath .. throneConfig.picture1 .. ".png")
	end

	local baseInfo = info.baseInfo
	if not baseInfo then 
		firstPanel:setVisible(false)
		return
	end
	txtName:setString(baseInfo.name)

	-- if self.isLoading then return end -- 正在加载
	-- self.isLoading = true
	local AvatarFactory = app:getClass("AvatarFactory")
	-- 加载完之后直接创建角色
	local function onCreateCharacter(params)
		if tolua.isnull(self) then return end
	    -- self.isLoading = false
	    if params ~= self._rightBaseInfo then return end -- 不是最新的baseInfo,就返回

	    local character = AvatarFactory.createHero(params)
	   	character:playAni({name = "mapidle"})
	    -- character:setScale(0.8)
	    local characterNode = championPanel:getChildByName("Node_1")
	    characterNode:removeAllChildren()
	    characterNode:addChild(character)
	    character:setTag(100)
	end

   	baseInfo.inBattle = false
   	baseInfo.mountID = 0

   	self._rightBaseInfo = baseInfo
   	
   	AvatarFactory.preloadHero(baseInfo, function()
   		onCreateCharacter(baseInfo)
   	end)

end

-- 更新当前显示
function ClassRef:updateCurrentStatus(throneGame)
	local today = app:getWeekDay()

	self._championReady:setShow(false)
	self._championSearch:setShow(false)
	self._championSeek:setShow(false)
	self._championForm:setShow(false)

	if self._curThroneInfo.day == today then -- 今天
		local status = throneGame:checkChampionStatus()

		if status == Enums.ChampionStatus.NOT_OPEN then -- 未开启报名
			-- do noghing
        elseif status == Enums.ChampionStatus.REGISTER then -- 报名阶段
            if not throneGame.register then -- 未报名
            	self._championSeek:setShow(true)
				-- 显示seek界面时，去更新队伍信息
				executeFunc(self._onOperate, "refreshTeamMemberList")
            else -- 已报名
                if throneGame.teamMemCount >= 3 then -- 队伍已满
                    self._championReady:setShow(true)
                    self._championReady:updateCharacter(self._throneTeam)
                    self._championReady:showRank(false)
                else -- 队伍未满
                    self._championSearch:setShow(true)
                end
            end

        else
        	self:reqThroneRankInfo()
        	self:reqFinalTeamInfo()
        end
		
	elseif self._curThroneInfo.day < today then -- 前面几天
		-- donothing
	end
end

function ClassRef:updateView(data, throneGame, throneTeam)
	self._curThroneInfo = data
	self._throneGame = throneGame
	self._throneTeam = throneTeam

	-- 更新左边冠军显示
	self:updateChampionCharacter()
	--更新当前状态
	self:updateCurrentStatus(throneGame)

	-- 添加定时器
	if self._cronsIdx then
		scheduler.cancelCron(self._cronsIdx)
		self._cronsIdx = nil
	end
	self._cronsIdx = scheduler.newCron(handler(self, self._tick), 1, true)
	self:_tick() -- 先执行一次tick
end

function ClassRef:_refreshTeamMemberList(team, isNewApplyerFlag)
	if not self._championSeek:isVisible() then return end
	self._championSeek:_refreshTeamMemberList(team, isNewApplyerFlag)
end

function ClassRef:_refreshNewApplyerFlag(visible)
	if not self._championSeek:isVisible() then return end
    self._championSeek:_refreshNewApplyerFlag( visible )
end

-- 更新胜负信息
function ClassRef:updateChampionRank(rankInfo)
	if not self._championReady:isVisible() then return end
	self._championReady:updateChampionRank(rankInfo)
end

-- 请求胜负信息
function ClassRef:reqThroneRankInfo()
	executeFunc(self._onOperate, "reqThroneRankInfo")
end

-- 请求决赛信息
function ClassRef:reqFinalTeamInfo()
	executeFunc(self._onOperate, "reqFinalTeamInfo", function(rankInfo, finalTeamInfo, myTeamIsKickOut, myTeamId)

		if cc.isDead(self) then
			return
		end
		if finalTeamInfo.isKnockOut then
			local rank = 0 
			if rankInfo then
				rank = rankInfo.rank
			end
			self._championForm:setShow(true)
			self._championForm:updateInfo(finalTeamInfo, myTeamIsKickOut, myTeamId, rank)
		elseif not self._throneGame:getRegister() then -- 未报名
			self._championForm:setShow(true)
			self._championForm:updateInfo(nil)
		else
			self._championReady:setShow(true)
			self._championReady:updateCharacter(self._throneTeam)
			self._championReady:showRank(true, rankInfo)
		end
		self:_tick() -- 先执行一次tick
	end)
end


-- 关掉界面时，移除定时器
function ClassRef:onExit()
    if self._cronsIdx then
        scheduler.cancelCron(self._cronsIdx)
        self._cronsIdx = nil
    end

    self.super.onExit(self)
end


return ClassRef
